<template>
	<div :class="['upload-more', { none: img.length && !isMore }]">
		<icon-plus />
		<input type="file" ref="uploadRef" class="upload-ipt" @change="handleUpload" :accept="accept" :limit="limit" :multiple="limit > 1" />
		<slot></slot>
	</div>
</template>
<script lang="ts" setup>
import { uploadFileCommon } from "@/api/common/index";
import { IconPlus } from "@arco-design/web-vue/es/icon";
const props = defineProps({
	text: {
		type: String,
		default: () => {
			return "上传文件";
		}
	},
	img: {
		type: Array || String,
		default: () => {
			return [] || "";
		}
	},
	accept: {
		type: String,
		default: () => {
			return ".jpg, .jpeg, .png, .pdf, .doc, .docx, .xls, .xlsx, .ppt, .pptx, .txt";
		}
	},
	disabled: {
		type: Boolean,
		default: () => {
			return false;
		}
	},
	// 是否直接上传
	isUpload: {
		type: Boolean,
		default: () => {
			return true;
		}
	},
	limit: {
		type: Number,
		default: () => {
			return 1;
		}
	},
	isMore: {
		type: Boolean,
		default: () => {
			return false;
		}
	}
});
const uploadRef = ref(null);
const emit = defineEmits(["handleUpload"]);

// 上传文件
const handleUpload = async (event) => {
	let files = []; // 上传文件列表
	files = event.target.files;
	if (!files || files.length === 0) {
		console.error("No files selected.");
		return;
	}
	const formData = new FormData();
	// 将每个文件添加到 FormData 中
	for (let i = 0; i < files.length; i++) {
		formData.append("file", files[i]);
		if (props.isUpload) {
			const str = files[i].name.lastIndexOf(".");
			const name = files[i].name.substring(0, str);
			const unit = files[i].name.substring(100, str);
			try {
				const res = await uploadFileCommon(formData);
				emit("handleUpload", { fileUrl: res?.data, fileName: name + unit });
			} finally {
			}
		} else {
			emit("handleUpload", files[i]);
		}
	}
	nextTick(() => {
		emit("handleUpload", formData);
		if (uploadRef?.value) {
			uploadRef.value.value = "";
		}
	});
};
</script>
<style lang="scss" scoped>
div {
	width: 100%;
	.text {
		color: #999;
	}
}
:deep(.arco-upload) {
	width: 80px;
	img {
		width: 80px;
		height: 80px;
	}
}
:deep(.arco-upload-list) {
	width: 80px;
	height: 80px;
	.arco-upload-list-picture {
		margin: 0;
	}
}
.upload-style {
	:deep(.arco-upload-dragger) {
		height: initial !important;
		width: initial !important;
		border: none;
		padding: 0;
	}
}
.upload-more {
	position: relative;
	display: inline-block;
	width: 80px;
	height: 80px;
	border: 1px dashed var(--color-neutral-3);
	background: var(--color-fill-2);
	display: flex;
	align-items: center;
	justify-content: center;
	img {
		width: 80px !important;
		height: 80px !important;
	}
	.upload-ipt {
		position: absolute;
		left: 0;
		top: 0;
		width: 100% !important;
		height: 100% !important;
		opacity: 0;
		cursor: pointer;
	}
	&.none {
		border: none;
		background: none;
		svg {
			display: none;
		}
	}
}
</style>
